#include "gamescene.h"
#include "movingobject.h"
#include "qpushbutton.h"
#include<QDebug>
#include<QMenuBar>
#include<qpainter.h>
#include<QPixmap>
#include <QMessageBox>
#include<QRect>
#include <QVBoxLayout>
#include<random>
#include<QThread>
#include <QRandomGenerator>
#include <QImage>
#include <QMediaPlayer>
#include <QUrl>
#include <QAudioOutput>
#include <QMediaDevices>
#include <QAudioDevice>
const int TARGET_WIDTH=70;
gamescene::gamescene(QWidget *parent)
    : QMainWindow{parent}
{   label = new QLabel(this);
    this->setFixedSize(1211,800);
    this->setWindowTitle("不能死啊啊啊");
    QMenuBar *bar=menuBar();//创建菜单栏
    setMenuBar(bar);
    QMenu*startmenu=bar->addMenu("设置");
    QAction *quitaction=startmenu->addAction("退出");
    QAction *restartaction=startmenu->addAction("重新开始");
     QAction *pauseaction = startmenu->addAction("暂停");
    QAction *continueaction=startmenu->addAction("继续");
    connect(quitaction, &QAction::triggered, this, [=](){
         this->close();
     });
    connect(restartaction,&QAction::triggered,this,[=](){
         this->close();
        gamescene*game=new gamescene;
        game->show();//movingObjectLabel->move(800, 400);
        anitimer->start();
        game->startmoving();
    });
    connect(pauseaction, &QAction::triggered,this, [=]() {
        if (!isPaused) {
            isPaused = true;
            ismoving = false;
            anitimer->stop(); // 停止动画定时器
            spawnTimer->stop();
            countdownTimer->stop();
            collisionTimer->stop();
            backgroundMusic->pause(); // 停止背景音乐
            qDebug() << "Game paused.";
        }
    });
    connect(continueaction, &QAction::triggered,this, [=]() {
        if (isPaused) { // 假设 isPaused 是一个标志变量，表示游戏是否暂停
            isPaused = false;
            ismoving = true;
            // 恢复游戏逻辑，例如重新启动定时器
            anitimer->start(); // 恢复动画定时器
        //   moveTimer->start(); // 恢复移动定时器
            spawnTimer->start();
            countdownTimer->start();
            collisionTimer->start();
            backgroundMusic->play();
        }
    });
//返回按键
    // 创建用于显示小人的 QLabel
    runningManLabel = new QLabel(this);
    runningManLabel->move(200, 495);
    // 设置小人显示的指定位置
    // 初始化动画定时器
    anitimer = new QTimer(this);
    connect(anitimer, &QTimer::timeout, this, &gamescene::updateRunningAnimation);
    anitimer->start(100);
    qDebug() << "Animation timer started!";// 每 100 毫秒更新一次动画
    // 初始化帧索引
    currentFrame = 0;

    // 初始化碰撞检测定时器
    collisionTimer = new QTimer(this);
    connect(collisionTimer, &QTimer::timeout, this, &gamescene::checkCollisions);
    collisionTimer->start(10); // 每 10ms 检测一次碰撞
    //物体移动
   // 初始化中心部件
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    //centralWidget->setLayout(layout); // 设置布局
    //setCentralWidget(centralWidget); // 设置为中心部件// 初始化图片路径
    imagePaths = {
        ":/picture/obstacle1.jpg",
        ":/picture/obstacle2.jpg",
        ":/picture/obstacle3.jpg"
    };
    // 初始化定时器
    spawnTimer = new QTimer(this);
    connect(spawnTimer, &QTimer::timeout, this, &gamescene::moveObject);
    //spawnTimer->start(2000); // 每 2 秒生成一个物体
    // 初始化倒计时显示
    countdownLabel = new QLabel(this);
    countdownLabel->setAlignment(Qt::AlignCenter);
    countdownLabel->setStyleSheet("font-size: 24px; color: red;");
    countdownLabel->setGeometry(500, 10, 200, 50); // 放置在顶部中间
    countdownLabel->setText("01:40"); // 初始显示 3 分钟

    // 初始化倒计时定时器
    countdownTimer = new QTimer(this);
    connect(countdownTimer, &QTimer::timeout, this, &gamescene::updateCountdown);
    remainingTime = 100; // 3 分钟（180 秒）
    isGameOver = false;
    // 初始化积分显
    scoreLabel = new QLabel(this);
    scoreLabel->setAlignment(Qt::AlignRight);
    scoreLabel->setStyleSheet("font-size: 24px; color: white;");
    scoreLabel->setText("Score: 0");
    scoreLabel->setGeometry(1000, 20, 200, 50); // 设置位置和大小
    // 初始化背景音乐播放器
    backgroundMusic = new QMediaPlayer(this);
    audioOutput1 = new QAudioOutput(this);
    backgroundMusic->setAudioOutput(audioOutput1);
    backgroundMusic->setSource(QUrl("qrc:/picture/background.mp3")); // 加载音乐文件
    audioOutput1->setVolume(0.5); // 50% 音量
    failMusic = new QMediaPlayer(this);
    audioOutput2 = new QAudioOutput(this);
    failMusic->setAudioOutput(audioOutput2);
    failMusic->setSource(QUrl("qrc:/picture/fail.mp3")); // 加载音乐文件
    audioOutput2->setVolume(0.5); // 50% 音量
    successMusic = new QMediaPlayer(this);
    audioOutput3 = new QAudioOutput(this);
    successMusic->setAudioOutput(audioOutput3);
    successMusic->setSource(QUrl("qrc:/picture/success.mp3")); // 加载音乐文件
    audioOutput3->setVolume(0.5); // 50% 音量
}

gamescene::~gamescene()
{
    // 如果定时器没有父对象，手动删除
    if (anitimer && anitimer->parent() == nullptr) {
        delete anitimer;
    }
    if (collisionTimer && collisionTimer->parent() == nullptr) {
        delete collisionTimer;
    }
    if (spawnTimer && spawnTimer->parent() == nullptr) {
        delete spawnTimer;
    }
    if (countdownTimer && countdownTimer->parent() == nullptr) {
        delete countdownTimer;
    }
    // 如果 runningManLabel 没有父对象，手动删除
    if (runningManLabel && runningManLabel->parent() == nullptr) {
        delete runningManLabel;
    }

    // 如果 movingObjects 中的对象没有父对象，手动删除
    for (MovingObject *obj : qAsConst(movingObjects)) {
        if (obj && obj->parent() == nullptr) {
            delete obj;
        }
    }
    QMutexLocker locker(&movingObjectsMutex);
    qDeleteAll(movingObjects);
    if (label) {
        label->deleteLater();
    }
    movingObjects.clear();
}

void gamescene:: paintEvent(QPaintEvent*){
    QPainter painter(this);
    QPixmap pix;
    pix.load("://picture/newgamebackground.jpg");
    painter.drawPixmap(0,0,this->width(),this->height(),pix);//拉伸成窗口大小
}
void gamescene::updateRunningAnimation()
{
    if (isPaused) {
        return; // 碰撞发生后停止小人动画
    }

    // 构建当前帧的图片路径
    QString imagePath = QString(":/picture/%1.jpg").arg(currentFrame);
    QPixmap pixmap(imagePath);

    if (!pixmap.isNull()) {
        // 计算图片的宽高比
        double aspectRatio = (double)pixmap.height() / pixmap.width();
        // 根据目标宽度和宽高比计算目标高度
        int targetHeight = static_cast<int>(TARGET_WIDTH * aspectRatio);

        // 等比例缩放图片
        pixmap = pixmap.scaled(TARGET_WIDTH, targetHeight, Qt::KeepAspectRatio);
        // 设置 QLabel 的背景为透明
        runningManLabel->setStyleSheet("background: transparent;");
        // 显示图片
        runningManLabel->setPixmap(pixmap);
        runningManLabel->setFixedSize(TARGET_WIDTH, targetHeight);
       runningManLabel->setMask(pixmap.mask()); // qDebug() << "Image loaded successfully:" << imagePath;
    } else {
       qDebug() << "Failed to load image:" << imagePath;
    }
    // 更新帧索引
    currentFrame = (currentFrame + 1) % frameCount;
   // qDebug() << "Current frame:" << currentFrame;
    // 处理跳跃逻辑
    QElapsedTimer jumpPauseTimer; // 用于记录跳跃完成的时间
    if (isJumping) {
        int currentMaxJumpHeight = (jumpCount == 1) ? maxJumpHeight / 1.5 : maxJumpHeight;
        if (jumpHeight < currentMaxJumpHeight) {
            runningManLabel->move(runningManLabel->x(), runningManLabel->y() - jumpStep); // 向上移动
            jumpHeight += jumpStep;
           // qDebug() << "Jumping - Height:" << jumpHeight << "Position:" << runningManLabel->x() << runningManLabel->y();
        } else {
            isJumping = false;
            isPausing = true; // 开始空中停留
            jumpPauseTimer.start(); // 记录当前时间
            //qDebug() << "Jump finished!";
        }
    } else if (jumpHeight > 0) {
        if (isPausing) {
            // 检查是否已经停留了 500 毫秒
            if (jumpPauseTimer.elapsed() >= 650) {
                isPausing = false; // 结束停留，开始下降
            }
        }
        else {
        int fallStep = jumpStep * 1.3;// 下降时的步长是上升时的2倍
        // 确保下降后 jumpHeight 不会小于 0
        if (jumpHeight - fallStep < 0) {
            fallStep = jumpHeight; // 只下降剩余的高度
        }
        runningManLabel->move(runningManLabel->x(), runningManLabel->y() + + fallStep); // 向下移动
        jumpHeight -=  fallStep;
        //qDebug() << "Falling - Height:" << jumpHeight << "Position:" << runningManLabel->x() << runningManLabel->y();

        // 如果人物回到地面，重置状态
        if (jumpHeight <= 0) {
            isOnGround = true;
            jumpCount = 0;
           // qDebug() << "Landed on the ground!";
           }
        }
    }
}
bool checkPixelCollision(const QImage &image1, const QRect &rect1, const QImage &image2, const QRect &rect2) {
    // 检查图片是否有效
    if (image1.isNull() || image2.isNull()) {
        qDebug() << "One or both images are null!";
        return false;
    }

    // 打印图片尺寸
    //qDebug() << "Image1 size:" << image1.size();
   // qDebug() << "Image2 size:" << image2.size();

    // 打印矩形区域
    //qDebug() << "Rect1:" << rect1;
    //qDebug() << "Rect2:" << rect2;

    // 计算两个矩形的重叠区域
    QRect overlap = rect1.intersected(rect2);
   // qDebug() << "Overlap before adjustment:" << overlap;
    if (overlap.isEmpty()) {
        qDebug() << "No overlap area between rectangles.";
        return false; // 没有重叠区域
    }

    // 确保重叠区域在图片范围内
    //overlap = overlap.intersected(QRect(0, 0, image1.width(), image1.height()));
    //overlap = overlap.intersected(QRect(0, 0, image2.width(), image2.height()));
    //qDebug() << "Overlap after adjustment:" << overlap;
    if (overlap.isEmpty()) {
        qDebug() << "Overlap area is outside image bounds.";
        return false;
    }

    // 遍历重叠区域的每个像素
    for (int y = overlap.top(); y <= overlap.bottom(); ++y) {
        for (int x = overlap.left(); x <= overlap.right(); ++x) {
            // 计算相对于每个图片的像素坐标
            QPoint pos1(x - rect1.left(), y - rect1.top());
            QPoint pos2(x - rect2.left(), y - rect2.top());

            // 检查坐标是否在图片范围内
            if (pos1.x() >= 0 && pos1.x() < image1.width() && pos1.y() >= 0 && pos1.y() < image1.height() &&
                pos2.x() >= 0 && pos2.x() < image2.width() && pos2.y() >= 0 && pos2.y() < image2.height()) {
                // 检查两个图片的像素是否都是非透明的
                if (image1.pixelColor(pos1).alpha() > 0 || image2.pixelColor(pos2).alpha() > 0) {
                    qDebug() << "Collision detected at pixel (" << x << "," << y << ")";
                    return true; // 碰撞发生
                }
            }
        }
    }

    qDebug() << "No collision detected in overlap area.";
    return false; // 没有碰撞
}
void gamescene::checkCollisions()
{// 获取小人的 QLabel 中的 QPixmap
    const QPixmap runningManPixmap = runningManLabel->pixmap();
    if (!runningManPixmap || runningManPixmap.isNull()) {
        qDebug() << "Running man pixmap is null or not loaded!";
        return;
    }

    // 将 QPixmap 转换为 QImage
    QImage manImage = runningManPixmap.toImage();

    // 获取跑步小人的矩形区域
    QRect manRect = runningManLabel->geometry();
    // 加锁保护 movingObjects
    QMutexLocker locker(&movingObjectsMutex);

    // 打印容器大小
   // qDebug() << "movingObjects 容器大小：" << movingObjects.size();

    // 使用 QMutableListIterator 安全地遍历和修改容器
    QMutableListIterator<MovingObject*> it(movingObjects);
    while (it.hasNext()) {
       MovingObject *obj = it.next();

        // 检查对象是否有效
        if (!obj || !obj->label) {
            qDebug() << "对象无效，移除";
            it.remove();
            continue;
        }

        // 打印物体当前 X 坐标
        //qDebug() << "物体当前 X 坐标：" << obj->objectX;

        // 如果物体到达目标位置，销毁它
        if (obj->objectX <= 130) {
            qDebug() << "物体到达目标位置，销毁对象：" << obj;
            if (obj->label!=0) { // 检查 label 是否有效
                if (obj->label) {
                    obj->label->hide();
                }
                obj->label->deleteLater(); // 销毁物体
            }
            it.remove();             // 从列表中移除
            delete obj;
            obj = nullptr; // 将指针置为 nullptr
            // 增加积分
            score += 10; // 假设每次成功跳过障碍物增加 10 分
            scoreLabel->setText(QString("Score: %1").arg(score));
            continue; // 跳过后续碰撞检测
        }

        // 检测物体是否与跑步小人碰撞
        if (obj) {
            // 获取物体的 QLabel 中的 QPixmap
            const QPixmap objPixmap = obj->label->pixmap();
            if (!objPixmap || objPixmap.isNull()) {
                qDebug() << "Object pixmap is null or not loaded!";
                continue;
            }// 检查指针是否有效
            obj->checkCollision(manRect);
            // 将 QPixmap 转换为 QImage
            QImage objImage = objPixmap.toImage();

            // 获取物体的位置和大小
            QRect objRect = obj->label->geometry();

            if (obj->collisionDetected) {
                if (checkPixelCollision(manImage, manRect, objImage, objRect)) {
                qDebug() << "碰撞发生，停止游戏";
                // 停止所有物体的移动
                for (MovingObject *obj : qAsConst(movingObjects)) {
                    if (obj) { // 检查指针是否有效
                        obj->stopMoving();
                    }
                }
                backgroundMusic->stop(); // 停止背景音乐
                // 停止定时器
                anitimer->stop();
                collisionTimer->stop();
                spawnTimer->stop();
                countdownTimer->stop();
                // 弹出游戏失败提示窗口
                failMusic->play();
                QMessageBox::critical(this, "游戏失败", "碰撞发生，游戏结束！\n当前积分为：" + QString::number(score));

                // 退出函数，不再检测其他物体
                return;
                }
            }
        }
    }
    //qDebug() << "碰撞检测完成";
}
void gamescene::startmoving()
{
    ismoving = true; // 启动物体移动
    spawnTimer->start(100);
    backgroundMusic->play();// 播放背景音乐

}
void gamescene::mousePressEvent(QMouseEvent *event) {
    //qDebug() << "Mouse button clicked:" << event->button();
    if (event->button() == Qt::LeftButton) {
        qDebug() << "Left mouse button clicked!";

        if (isOnGround) {
            // 一段跳
            isOnGround = false;
            jumpCount = 1;
            isJumping = true;
            qDebug() << "First jump!";
        } else if (jumpCount == 1) {
            // 二段跳
            jumpCount = 2;
            isJumping = true;
            qDebug() << "Second jump!";
        } else {
            // 不允许更多段跳
            qDebug() << "Cannot jump more than twice!";
        }
    }
}
void gamescene::moveObject()
{   // 如果倒计时未启动，启动它
    if (!countdownTimer->isActive()) {
        countdownTimer->start(1000); // 每秒触发一次
    }

     QMutexLocker locker(&movingObjectsMutex);
    // 随机选择一个图片路径
    std::uniform_int_distribution<int> dist(0, imagePaths.size() - 1);
    QString imagePath = imagePaths[dist(gen)];

    //qDebug() << "Spawning object with image path:" << imagePath;

    // 创建 MovingObject 实例，传入图片路径
    MovingObject *obj = new MovingObject(imagePath, centralWidget());
    if (!obj) {
       // qDebug() << "Failed to create MovingObject!";
        return;
    }

    // 加载图片并缩放
    QPixmap objectPixmap(imagePath); // 加载图片
    if (objectPixmap.isNull()) {
        qDebug() << "Failed to load image:" << imagePath;
        delete obj;
        return;
    }
    objectPixmap = objectPixmap.scaled(60, 90, Qt::KeepAspectRatio); // 缩放图片
    obj->label->setStyleSheet("background: transparent;");
    obj->label->setPixmap(objectPixmap); // 设置图片到 QLabel
    obj->label->setMask(objectPixmap.mask());
    obj->label->adjustSize(); // 调整 QLabel 大小以适应图片
    obj->label->show(); // 显式显示 QLabel
    qDebug() << "Scaled image size:" << objectPixmap.size();

    obj->objectX = 800; // 随机生成初始 X 位置
    // 定义两个不连续的范围
    int range1Min = 535, range1Max = 545;
    int range2Min = 420, range2Max = 460;
    // 生成一个随机数，决定选择哪个范围
    int rangeChoice = QRandomGenerator::global()->bounded(0, 5); // 生成 0 或 1 或 2
    // 根据选择的范围生成随机数
    int randomValue;
    if (rangeChoice == 0) {
        randomValue = QRandomGenerator::global()->bounded(range2Min, range2Max + 1); // 范围 2
    }
    else{randomValue = QRandomGenerator::global()->bounded(range1Min, range1Max + 1);} // 范围 1

    // 设置对象的 Y 位置
    obj->objectY = randomValue;
    //qDebug() << "Object initial position:" << obj->objectX << obj->objectY;

    // 设置物体的目标位置
    obj->targetX = 130; // 目标 X 位置
    obj->targetY =obj->objectY; // 目标 Y 位置

    // 移动物体到初始位置
    obj->label->move(obj->objectX, obj->objectY);
   // qDebug() << "Object moved to initial position.";

    // 启动物体的移动
    obj->startMoving();
   // qDebug() << "Object started moving.";

    // 将物体添加到物体列表中
    movingObjects.append(obj);
    qDebug() << "Object added to movingObjects list.";
    // 生成随机时间（1000、2000、3000 或 4000 毫秒）
    std::random_device rd; // 随机种子
    std::mt19937 gen(rd()); // 随机数引擎
    std::uniform_real_distribution<> dis(1.5, 3); // 生成 1 到 4 的随机整数
    int randomTime = dis(gen) * 1000;

    // 重新启动 spawnTimer
    spawnTimer->start(randomTime);
   qDebug() << "Next object will spawn in:" << randomTime << "ms";
}
void gamescene::updateCountdown()
{
    if (remainingTime > 0) {
        remainingTime--;
        int minutes = remainingTime / 60;
        int seconds = remainingTime % 60;
        countdownLabel->setText(QString("%1:%2")
      .arg(minutes, 2, 10, QChar('0'))
     .arg(seconds, 2, 10, QChar('0')));
    } else {
        countdownTimer->stop();
        checkGameResult(); // 检查游戏结果
    }
}
void gamescene::checkGameResult()
{
    if (!isGameOver) {
        bool isVictory = true;

        // 检查是否有障碍物到达目标位置
        for (MovingObject *obj : qAsConst(movingObjects)) {
            if (obj->objectX < 200) {
                isVictory = false;
                break;
            }
        }

        // 如果游戏胜利，停止定时器并隐藏所有物体
        if (isVictory) {
            anitimer->stop(); // 停止动画定时器
            spawnTimer->stop();
            backgroundMusic->stop(); // 停止背景音乐
            // 隐藏并销毁所有物体
            for (MovingObject *obj : qAsConst(movingObjects)) {
                if (obj && obj->label) {
                    obj->label->hide();      // 隐藏物体
                    obj->label->deleteLater(); // 销毁物体
                }
                delete obj; // 释放 MovingObject 对象
            }
            movingObjects.clear(); // 清空容器
            successMusic->play();
            showVictoryScreen(); // 显示胜利界面
        }
        isGameOver = true;
    }
}
void gamescene::showVictoryScreen()
{
    QDialog *victoryDialog = new QDialog(this);
    victoryDialog->setWindowTitle("游戏胜利");
    victoryDialog->setFixedSize(400, 500);
// 设置背景图片
    QPixmap background("://picture/success.jpeg"); // 背景图片路径
    if (!background.isNull()) {
        victoryDialog->setAutoFillBackground(true);
        QPalette palette = victoryDialog->palette();
        palette.setBrush(QPalette::Window, background.scaled(victoryDialog->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
        victoryDialog->setPalette(palette);
    } else {
        qWarning() << "Failed to load background image!";
    }
    QLabel *victoryLabel = new QLabel(victoryDialog);
    victoryLabel->setAlignment(Qt::AlignCenter);
    victoryLabel->setStyleSheet("font-family: 宋体; font-size: 23px; color: white;""margin-top: 45px;");
    victoryLabel->setText(QString("恭喜你，游戏胜利！\n成功到家\n积分：%1").arg(score));
    QVBoxLayout *layout = new QVBoxLayout(victoryDialog);
    layout->addWidget(victoryLabel);
    victoryDialog->setLayout(layout);

    victoryDialog->exec();
}
